<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="layuiadmin/plugins/input-tag/inputTag.css">
    <script src="layuiadmin/plugins/input-tag/inputTag.js"></script>
    <script type="text/javascript" src="js/ueditor-plus/ueditor.config.js"></script>
    <script type="text/javascript" src="js/ueditor-plus/ueditor.all.js"></script>
    <script type="text/javascript" charset="utf-8" src="js/ueditor-plus/lang/zh-cn/zh-cn.js?58c38108"></script>
    <script th:src="@{/}+'js/tool.js'"></script>
    <style type="text/css">
        .layui-form .layui-form-item{
            width:90%;
        }
        .layui-input-inline{
            width:200px!important
        }
    </style>

</head>
<body>
<div class="layui-tab layui-tab-brief" lay-filter="tabfilter">
    <ul class="layui-tab-title">
        <li class="layui-this">题目信息</li>
        <li>选项列表</li>
        <li>组卷记录</li>
    </ul>
    <div class="layui-tab-content">
        <div class="layui-tab-item layui-show">
            <div th:replace="ksxt/lib/question-fr::info"></div>
        </div>
        <div class="layui-tab-item">
            <table class="layui-hide"  id="choice-table" lay-filter="choice-table"></table>
        </div>
        <div class="layui-tab-item">
            <table class="layui-hide"  id="join-table" lay-filter="join-table"></table>
        </div>
    </div>
</div>
<script src="layuiadmin/plugins/xm-select/xm-select.js"></script>

<script>
    var id = `[[${id}]]`;
    let delFlag = `[[${delFlag}]]`
    $("#btndiv").hide();
    (function () {
        var ue = UE.getEditor('tigan',{
            zIndex:1
        });
        var daan = UE.getEditor('daan', {
            zIndex:1
        });
        var jiexi = UE.getEditor('jiexi', {
            zIndex:1
        });
        if(id){
            var entity = getEntityInfo(id,"libQuestion/getById");
            ue.ready(function(){
                try{
                    UE.getEditor('tigan').setContent(entity.text, false)
                }catch (e){

                }
            });
            daan.ready(function(){
                try{
                    UE.getEditor('daan').setContent(entity.answerText, false)
                }catch (e){

                }
            });
            jiexi.ready(function(){
                try{
                    UE.getEditor('jiexi').setContent(entity.analysis, false)
                }catch (e){

                }
            });
        }

    })();
    // CKEDITOR.replace('tigan',
    //     {
    //         filebrowserImageUploadUrl: "uploadImage/upload?winname=editwin",
    //         height: 150
    //     });
    // CKEDITOR.replace('jiexi',
    //     {
    //         filebrowserImageUploadUrl: "uploadImage/upload?winname=editwin",
    //         height: 150
    //     });
    // CKEDITOR.replace('daan',
    //     {
    //         filebrowserImageUploadUrl: "uploadImage/upload?winname=editwin",
    //         height: 150
    //     });

    layui.use(['form', 'table', 'laydate','inputTag'], function(){
        var form = layui.form
            ,table = layui.table
            ,inputTag = layui.inputTag
            ,layer = layui.layer;

        createSelect("repeatable","ignoreRepeat",form,1,'请选择');
        createSelect("test-phase","testPhase",form,'','请选择');
        createSelect("paper-type","paperType",form,'','请选择');
        createSelect("test-type","testType",form,1,'请选择');
        createSelect("question-source","source",form,1,'请选择');
        createSelect("question-difficulty","difficulty",form,1,'请选择');
        createSelect("content-type","contentType",form,1,'请选择');
        createSelect("paper-lg","lg",form,1,'请选择');
        createSelect("semester","semester",form,'','请选择');
        createSelect("student-type","studentType",form,'','请选择');
        select('grade/getPageList?limit=30&page=1' , 'grade',form,'name','id')
        select('pian/getPageList?limit=30&page=1' , 'pianId',form,'name','id')
        select('knowledgePoint/getPageList?limit=1000&page=1' , 'knowledge1',form,'name','id')
        select('college/getPageList?limit=30&page=1' , 'collegeId',form,'name','id')
        select('libCategory/getPageList?limit=30&page=1' , 'categoryId',form,'name','id')
        select('major/getPageList?limit=30&page=1' , 'majorId',form,'name','id')
        select('gradeYear/getPageList?limit=30&page=1' , 'gradeYear',form,'name','id')
        let cols1 = [
            {type: 'checkbox'}
            ,{field: 'indexLetter',title: "索引",width:80}
            ,{field: 'text', title: "文本"}
            ,{field: 'rightTxt',title: "是否正确",width:90}
            ,{field: 'answerText',title: "答案说明",width:290}
        ];
        let cols2 = [
            {type: 'checkbox'}
            ,{field: 'indexLetter',title: "索引",width:80}
            ,{field: 'text', title: "文本"}
            ,{field: 'answerText',title: "答案说明",width:490}
        ];
        let cols = cols1;
        form.on("radio(questionType)",function (data){
            let type = data.value;
            let tab2 = $(".layui-tab-title li:eq(1)");
            let rowLength = $('div[lay-id=choice-table] tr[data-index]').length;
            $("#daandiv,#jiexidiv").hide();
            if(type==='5'){
                tab2.html("小题列表（"+rowLength+"）");
                cols = cols2;
                tab2.show();
                $("#daandiv,#jiexidiv").show();
            }else if(type==='4'){
                $("#daandiv,#jiexidiv").show();
                tab2.hide();
            }else{
                if(type<=2){
                    cols = cols2;
                }else{
                    cols = cols1;
                }
                tab2.html("选项列表（"+rowLength+"）");
                tab2.show();
            }
            initTable();
        })
        let klps = [];
        $(".klp1").on("click",function (){
            top.layer.open({
                id:"openklp",
                type: 2,
                title:'选择知识点',
                area:['1100px','600px'],
                content:  'rooter?url=ksxt/lib/select-knowledge',
                btn:['选择','关闭'],
                yes:function(index,layero){
                    let oldv = $("#knowledge").val();
                    let oldn = $("#klp1").text();
                    var iframeWin = top[layero.find('iframe')[0]['name']];
                    let ids = iframeWin.getIds();
                    let idset = new Set(),nameset = new Set();
                    if(oldv.length>0){
                        var idarr = oldv.split(",");
                        var namearr = oldn.split(",");
                        idarr.forEach(x=>idset.add(x));
                        namearr.forEach(x=>nameset.add(x))
                    }
                    for(var i=0;i<ids.length;i++){
                        idset.add(ids[i].id+"");
                        nameset.add(ids[i].name)
                    }
                    if(idset.size===0){
                        top.layer.close(index);
                        return false;
                    }
                    $("#knowledge").val([...idset].join(","))
                    $(".fairy-tag-container span").remove();
                    inputTag.render({
                        elem: '.klp1',
                        data: [...nameset],
                        removeKeyNum: 8,
                        createKeyNum: 27,
                        onChange:function (v){

                            $("#klp1").text(v.join(","));
                        }
                    });
                    top.layer.close(index);
                    return false
                }
            });
        })
        function initTable(){
            table.render({
                elem: '#choice-table'
                ,height: 640
                ,url: 'libChoice/getPageList'
                ,title: '选项列表'
                ,toolbar: '#toolbar'
                ,where:{questionId :id||-1,page:1,limit:100,delFlag:delFlag}
                ,defaultToolbar:false
                ,cols: [
                    cols
                ]
                ,done:function(){
                    enableRowClick(table,form,'choice-table',"choice-table");
                    let rowLength = $('div[lay-id=choice-table] tr[data-index]').length;
                    let tab2 = $(".layui-tab-title li:eq(1)");
                    tab2.html(tab2.html().substring(0,4) + "（" + rowLength + "）");
                }
            });
        }

        setTimeout(function (){
                initTable();
            },1
        )
        table.on('toolbar(choice-table)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id);
            switch(obj.event){
                case 'add':
                    let type = $(":radio[name=questionType]:checked").val();
                    if(!type){
                        top.layer.msg("请选择题型");
                        return false;
                    }
                    var t = "选项"
                    let url = 'rooter?url=ksxt/lib/add-choice&libQuestionId='+id;
                    if(type==='4'||type==='5'){
                        t = "小题"
                        url = 'rooter?url=ksxt/lib/add-choice2&libQuestionId='+id;
                    }

                    top.layer.open({
                        id:"choicewin",
                        type: 2,
                        title:'增加' + t,
                        area:['1000px','760px'],
                        content:  url,
                        btn:['保存','关闭'],
                        yes:function(index,layero){
                            var dataForm = top.layer.getChildFrame('form', index);
                            dataForm.find("#submitBtn").click();
                            return false
                        }
                    });
                    break;
                case 'delete':
                    var data = checkStatus.data;
                    if(data.length>0){
                        var values = {};
                        var ids=[];
                        $.each(data,function(i,v){
                            ids.push(v.id);
                        })
                        values['ids'] = ids.join(",");

                        layer.confirm('确定要删除当前行么?', {icon: 3, title:'提示'}, function(index){
                            axios.post("libChoice/delete",values).then(res=>{
                                var data = res.data;
                                table.reload('choice-table');
                                layer.close(index)
                            })
                        });
                    }else{
                        layer.msg("请选择操作数据!")
                    }
                    break;
                case 'edit':
                    var data2 = checkStatus.data;
                    if(data2.length>0){
                        editChoice(data2[0].id);
                    }else{
                        layer.msg("请选择操作数据！")
                    }
                    break;
            };
        });
        form.on('submit(submitme)', function(data){
            var text = UE.getEditor('tigan').getContent();
            // var text = CKEDITOR.instances.tigan.getData();
            // text = substractText(text);
            // if($(text).text()!=''){
            //     text = $(text).text();
            // }
            if(text.length<5){
                top.layer.msg("题干字数不能小于5");
                return false
            }
            var analysis = UE.getEditor('jiexi').getContent();
            var daan = UE.getEditor('daan').getContent();
            // var analysis = CKEDITOR.instances.jiexi.getData();
            // analysis = substractText(analysis);
            // var daan = CKEDITOR.instances.daan.getData();
            // daan = substractText(daan);
            var klpselects = $("select[name=knowledge1] option");
            var map = {};
            klpselects.each(function (i,v){
                map[v.text] = v.value;
            })
            var klpIds = [],klp1 = $("#klp1").text();
            if(klp1.length>0){
                var kps = klp1.split(",");
                for(var k=0;k<kps.length;k++){
                    klpIds.push(map[kps[k]]);
                }
                $("#knowledge").val(klpIds.join(","))
            }else{
                $("#knowledge").val('')
            }

            var values = {text:text,analysis:analysis,answerText:daan};
            $(":input").each(function(i,v){

                if(v.name){
                    if(v.name=='questionType'){
                        if($(v).prop("checked")){
                            values[v.name] = $(v).val();
                        }
                    }else{
                        values[v.name] = v.value;
                    }
                }
            })

            if(!values.questionType){
                top.layer.msg("请选择题型")
                return false;
            }
            axios.post("libQuestion/save",values).then(res=>{
                if(res.data.code==1){
                    layer.msg(ret.msg);
                }else{
                    let win = getTabWin('openwin12');
                    if(!win){
                        win = getTabWin();
                    }
                    win.loadGrid('main-table');
                    layer.msg("保存成功");
                    loadData()
                    var index = top.layer.getFrameIndex(window.name);
                    // top.layer.close(index);
                }
            })
            return false;
        });
        window.editTabTitle = function (type){
            let tab2 = $(".layui-tab-title li:eq(1)");
            if(type==='4'||type==='5'){
                tab2.html("小题列表");
                tab2.hide();
            }else{
                tab2.html("选项列表");
                tab2.show();
            }

        }

        if(id){

            $(":radio[name=questionType]").prop("disabled",true)
            loadData();

            let type = $(":radio[name=questionType]:checked").val();
            editTabTitle(type)
            table.render({
                elem: '#join-table'
                ,height: 630
                ,url: 'paper/getPageList'
                ,where:{libQuestionId:id}
                ,title: '试卷列表'
                ,page: true
                ,cols: [
                    [
                        {type: 'numbers'}
                        ,{field: 'name', title: "试卷名称",width:230}
                        ,{field: 'code',title: "编号",width:90}
                        ,{field: 'categoryName',title: "考试科目",width:220}
                        ,{field: 'collegeName',title: "学院/系",width:170}
                        ,{field: 'majorName',title: "学期学年",width:200,templet:function (d){
                            return d.gradeYearName + d.semesterTxt;
                        }}
                        ,{field: 'testTypeTxt',title: "考试方式",width:110}
                        ,{field: 'howlong',title: "考试时长",width:120}
                        ,{field: 'stateTxt',title: "记录状态",width:120}
                        ,{field: 'createTime', title: "登记时间",width:170}
                    ]
                ]
                ,done:function(res){
                    let tab3 = $(".layui-tab-title li:eq(2)");
                    tab3.html("组卷记录（"+ res.count+"）");
                }
            });
        }else{
            $("ul.layui-tab-title li:eq(2)").hide();
            id = snowId();
            $("#id").val(id);
            select('chapter/getPageList?limit=0&page=1', 'chapterId',form,'name','id')
            select('jie/getPageList?limit=0&page=1' , 'jieId',form,'name','id')
            $.ajax({
                url:"libQuestion/getMaxOrderno",
                type:'get',
                dataType:'html',
                success: function(res){
                    $("#orderno").val(parseInt(res) + 1);
                }
            })
        }
        form.on("select(pianId)",function(data){
            select('chapter/getPageList?limit=50&page=1&pianId='+data.value , 'chapterId',form,'name','id')
            form.on("select(chapterId)",function(data){
                select('jie/getPageList?limit=50&page=1&chapterId='+data.value , 'jieId',form,'name','id')
            })
            select('jie/getPageList?limit=0&page=1' , 'jieId',form,'name','id')
        })
        // if(tags){
        //     inputTag.render({
        //         elem: '.tag1',
        //         data: tags,
        //         removeKeyNum: 8,
        //         createKeyNum: 27,
        //         onChange:function (v){
        //
        //             $("#tag1").text(v.join(","));
        //         }
        //     });
        // }

        if(klps){
            inputTag.render({
                elem: '.klp1',
                data: klps,
                removeKeyNum: 8,
                createKeyNum: 27,
                onChange:function (v){
                    $("#klp1").text(v.join(","));
                }
            });
        }
        function loadData(){
            var entity = getEntityInfo(id,"libQuestion/getById");
            select('chapter/getPageList?limit=30&page=1&pianId='+ entity.pianId, 'chapterId',form,'name','id')
            select('jie/getPageList?limit=30&page=1&chapterId='+entity.chapterId , 'jieId',form,'name','id')
            form.on("select(chapterId)",function(data){
                select('jie/getPageList?limit=50&page=1&chapterId='+data.value , 'jieId',form,'name','id')
            })
            // if(entity.tagName)
            //     tags = entity.tagName.split(",");
            if(entity.knowledgeName){
                klps = entity.knowledgeName.split(",");
            }

            // CKEDITOR.instances.daan.setData(entity.answerText);
            // CKEDITOR.instances.tigan.setData(entity.text);
            // CKEDITOR.instances.jiexi.setData(entity.analysis);
            form.val("myform",entity);
            if(entity.questionType==4||entity.questionType==5){
                // if(entity.questionType==5){
                //     $('#daandiv,#jiexidiv').hide();
                // }
                cols = cols2;
            }else{
                if(entity.questionType<=2){
                    cols = cols2;
                }else{
                    cols = cols1;
                }
                $('#daandiv,#jiexidiv').hide();
            }

        }
        window.loadGrid = function (){
            table.reload("choice-table");
        }

    })
    function editChoice(id){
        let type = $(":radio[name=questionType]:checked").val();
        if(!type){
            top.layer.msg("请选择题型");
            return false;
        }
        let url = "rooter?url=ksxt/lib/add-choice&id="+id;
        if(type==='5'){
            url = "rooter?url=ksxt/lib/add-choice2&id="+id;
        }
        top.layer.open({
            id:"choicewin",
            type: 2,
            title:'修改选项信息',
            area:['1000px','760px'],
            content:  url,
            btn:['保存','关闭'],
            yes:function(index,layero){
                var dataForm = top.layer.getChildFrame('form', index);
                dataForm.find("#submitBtn").click();
                return false
            }
        });
    }
    function revalue(){
        // CKEDITOR.instances.daan.setData('');
        // CKEDITOR.instances.tigan.setData('');
        // CKEDITOR.instances.jiexi.setData('');
        $("form")[0].reset();
        id = snowId();
        $("#id").val(id);
    }
</script>
<script type="text/html" id="toolbar">
    <div class="layui-btn-group">
        <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="add"><i class="layui-icon layui-icon-addition"></i>增加</button>
        <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>修改</button>
        <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="delete"><i class="layui-icon layui-icon-delete"></i>删除</button>
    </div>
</script>
</body>
</html>